<?php

namespace App\Jobs;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsTag;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;

class SearchEnginePushJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $common_base_post_url = '';
    protected $common_base_topic_url = '';
    protected $common_base_circle_url = '';
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function baidu_post_push(){
        //百度推送
        $baidu_cursor = Settings::get('seo_post_push_baidu_cursor', 0);
        $baidu_url = 'http://data.zz.baidu.com/urls?site='.env('APP_URL').'&token='.Settings::get('seo_push_baidu_token');
        // 获取待推送链接
        $baidu_posts = WxPost::where('id', '>', $baidu_cursor)->orderBy('id', 'asc')->limit(100)->get(['id', 'circle_id']);
        $baidu_max_post_id = 0;
        $baidu_needle_urls = [];
        if($baidu_posts){
            foreach ($baidu_posts as $post){
                if($post->id > $baidu_max_post_id){
                    $baidu_max_post_id = $post->id;
                }
                $tagsIds = WxPostsTag::where('posts_id', $post->id)->pluck('tags_id');//话题ID列表
                if($tagsIds){
                    foreach ($tagsIds as $tag_id){
                        $baidu_needle_urls[] = $this->common_base_topic_url . $tag_id;
                    }
                }
                $baidu_needle_urls[] = $this->common_base_circle_url . $post->circle_id;

                $baidu_needle_urls[] = $this->common_base_post_url . $post->id;
            }

            // 去重
            $baidu_needle_urls = array_unique($baidu_needle_urls);
            $baidu_body = implode("\n", $baidu_needle_urls);
            $baidu_res = Http::withBody(
                $baidu_body, 'text/plain'
            )->post($baidu_url);
            if($baidu_res->successful()){
                Settings::set('seo_post_push_baidu_cursor', $baidu_max_post_id);
            }
            _logger_(__file__, __line__, $baidu_res->json());
        }
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_10__;
        if(!$__MINI_GLOBAL_PAYCODE_10__){
            return;
        }
        // 公共
        $this->common_base_post_url = env('APP_URL') . '/single/';
        $this->common_base_topic_url = env('APP_URL') . '/tag/';
        $this->common_base_circle_url = env('APP_URL') . '/circle/';

        $this->baidu_post_push();

    }
}
